package jp.ne.iforce.android.jschatest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

public class ServerRegist{

	public String REGIST_URL = "http://192.168.1.221/jscha/regist.php";

	public int regist(String rid,String nick,Context context){

		//コマンド
		String COMMAND = "regist";

		//Macアドレス
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String MAC_ADDRESS = wifiInfo.getMacAddress();

		//ANDROID_ID
		//※Garaxy系はすべての製品が同じANDROID_ID
		//AndroidMarcketでGoogleアカウントログイン時に生成される。（端末リセットで変更される）
		String ANDROID_ID = Settings.Secure.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
		if(ANDROID_ID == null){
			ANDROID_ID = "NULL";
		}
		//※SIMなし端末はNULL
		TelephonyManager mTelephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		String IMEI = mTelephonyMgr.getDeviceId();
		String IMSI = mTelephonyMgr.getSubscriberId();
		String PHONE_NUMBER = mTelephonyMgr.getLine1Number(); // Requires READ_PHONE_STATE
        String SIM_SERIAL = mTelephonyMgr.getSimSerialNumber(); // Requires READ_PHONE_STATE

        //使える？
        Integer HASH_CODE = mTelephonyMgr.hashCode();

        //シリアルID(端末番号)
        //※2.3 (Gingerbread)以降から使用可能
        String SERIAL = android.os.Build.SERIAL;

        //IPアドレス
        String IP_ADDRESS = getIPAddr();

		Log.w("rid",""+rid);
		Log.w("nick",""+nick);
		Log.w("COMMAND",""+COMMAND);

		Log.w("IP_ADDRESS",""+IP_ADDRESS);
		Log.w("MAC_ADDRESS",""+MAC_ADDRESS);
		Log.w("ANDROID_ID",""+ANDROID_ID);
		Log.w("IMEI",""+IMEI);
		Log.w("IMSI",""+IMSI);
		Log.w("PHONE_NUMBER",""+PHONE_NUMBER);
		Log.w("SIM_SERIAL",""+SIM_SERIAL);
		Log.w("IMSI",""+IMSI);
		Log.w("HASH",""+HASH_CODE);
		Log.w("SERIAL",""+SERIAL);


    	ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    	params.add(new BasicNameValuePair("command", COMMAND));
    	params.add(new BasicNameValuePair("macaddr", MAC_ADDRESS));
    	params.add(new BasicNameValuePair("imei", ANDROID_ID));
    	params.add(new BasicNameValuePair("regid", rid));
    	params.add(new BasicNameValuePair("nickname", nick));
    	params.add(new BasicNameValuePair("ipaddr", IP_ADDRESS));

    	HttpPost httpPost = new HttpPost(REGIST_URL);
    	int statusCode = 500;

    	try {
			httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");// ヘッダを設定

			DefaultHttpClient client = new DefaultHttpClient();
	    	HttpResponse httpResponse = client.execute(httpPost);

	    	statusCode = httpResponse.getStatusLine().getStatusCode();

	    	HttpEntity entity = httpResponse.getEntity();
	    	String response = EntityUtils.toString(entity);

	    	entity.consumeContent();
	    	client.getConnectionManager().shutdown();

	    	String resStr = statusCode +":"+response;
	    	Log.w("RESPONSE",""+resStr);


		} catch (UnsupportedEncodingException e1) {
			// TODO 自動生成された catch ブロック
			e1.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}


		return statusCode;

	}

	private String getIPAddr(){
	    Enumeration<NetworkInterface> interfaces = null;
		try {
			interfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if(interfaces != null){
		    while(interfaces.hasMoreElements()){
		        NetworkInterface network = interfaces.nextElement();
		        Enumeration<InetAddress> addresses = network.getInetAddresses();
		        while(addresses.hasMoreElements()){
		        	InetAddress in = addresses.nextElement();
		            String address = in.getHostAddress();
		            if(!"127.0.0.1".equals(address) && !"0.0.0.0".equals(address) && in.getAddress().length == 4){
		                return address;
		            }
		        }
		    }
        }
	    return "127.0.0.1";
	}
}